// pages/decoration-form/decoration-form.js
import request from "../../../utils/request"
Page({
  data: {
    formData: {
      houseId: 0,
      room: "1栋1单元1层101",
      owner: "张* (137****9988)",
      contractor: {
        managerName: "",
        managerPhone: "",
        licensePlate: "",
        startDate: "",
        duration: "",
        renovationType: "",
        renovationProducts: "",
        license1:"",
        license2:""
      },
      products: [],
      notes: "",
    },
    contractFiles: [],
    certificateFiles: [],
    agreed: false,
    submitting: false,
    canSubmit: true,

    // 选择器相关
    showDatePopup: false,
    showTypePopup: false,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    fileList: [], // 已上传的文件列表
    limit: 2, // 最大上传数量
    acceptType: ['image/png', 'image/jpeg'], // 允许上传的文件类型
    maxSize: 5 * 1024 * 1024, // 最大文件大小（5MB）
    disabled: false, // 是否禁用上传
    showTip: true, // 是否显示上传提示
    fileSize: 5, // 文件大小限制（单位：MB）
    fileType: ['png', 'jpg'] ,// 文件类型限制,
    baseUrl: 'http://localhost:8080',
    uploadFileUrl: '/common/upload',
    myHouses:{},
    // 选项数据
    houseOptions: [
      { text: "城市花园1栋1单元1层101", value: "1" },
      { text: "城市花园1栋2单元2层201", value: "2" },
      { text: "城市花园2栋1单元3层301", value: "3" },
    ],
    showHouse:false,
  },

  onLoad() {
    this.loadUserHouses()
  },

// 合同文件上传
async uploadFile(e) {
  const { file } = e.detail;
  const { baseUrl, uploadFileUrl, headers } = this.data;
  const token = wx.getStorageSync('token');
  
  try {
    const res = await new Promise((resolve, reject) => {
      wx.uploadFile({
        url: baseUrl + uploadFileUrl,
        filePath: file.tempFilePath,
        name: 'file',
        header: {
          "Content-Type": "multipart/form-data",
          'Authorization': token ? `Bearer ${token}` : ''
        },
        success: resolve,
        fail: reject
      });
    });
    
    if (res.statusCode === 200) {
      const response = JSON.parse(res.data);
      if (response.code === 200) {
        // 构造文件对象
        const fileItem = {
          url: `http://localhost:8080${response.fileName}`, // 下载地址
          name: response.originalFilename, // 原始文件名
          status: 'done', // 上传状态
          message: '上传成功', // 状态提示
          // 如果需要预览，可以保留原始文件路径
          tempFilePath: file.tempFilePath,
          fileName:response.fileName
        };
        // 更新certificateFiles数组
        this.setData({
          certificateFiles: [...this.data.certificateFiles, fileItem]
        });

        this.updateLicenseFields()
        
        return {
          success: true,
          fileName: response.fileName,
          fileUrl: response.url,
          originalName: response.originalFilename
        };
      }
    }
    return { success: false, message: res.data };
  } catch (error) {
    console.error('上传失败:', error);
    return { success: false, message: '网络错误' };
  }
},

  // 处理上传成功
  handleUploadSuccess(response, file) {
    const newFile = {
      ...file,
      url: response.fileName,
      status: 'done',
      message: '上传成功'
    };
    
    const fileList = [...this.data.fileList, newFile];
    this.setData({ fileList });
    this.triggerEvent('update', { value: fileList.map(f => f.url).join(',') });
    wx.showToast({ title: '上传成功', icon: 'success' });
  },

  // 合同文件删除
  onContractDelete(e) {
    const { index } = e.detail
    const { contractFiles } = this.data

    contractFiles.splice(index, 1)
    this.setData({ contractFiles })
  },

  async getMyHouses(){
    const req = await request.get("/property/house/myHouses")
  },

  // 显示房屋选择器
  showHousePicker() {
    this.setData({ showHouse: true })
  },

  // 关闭房屋选择器
  closeHousePicker() {
    this.setData({ showHouse: false })
  },

  // 确认房屋选择
  onHouseConfirm(e) {
    const { value, index } = e.detail
    const selectedHouse = this.data.houseOptions[index]
    console.log(selectedHouse)
    this.setData({
      "formData.houseId": selectedHouse.value,
      "formData.houseAddress": selectedHouse.text,
      showHouse: false,
    })
    console.log(this.data.formData.houseId)
  },

  // 证照文件上传
onCertificateUpload(e) {
  const { file } = e.detail
  const { certificateFiles } = this.data

  // 模拟上传
  certificateFiles.push({
    ...file,
    url: file.url || file.path,
  })

  this.setData({ certificateFiles })
  
  // 更新 license1 和 license2
  this.updateLicenseFields()
},

// 证照文件删除
onCertificateDelete(e) {
  const { index } = e.detail
  const { certificateFiles } = this.data

  certificateFiles.splice(index, 1)
  this.setData({ certificateFiles })
  
  // 更新 license1 和 license2
  this.updateLicenseFields()
},

// 更新 license1 和 license2 字段
updateLicenseFields() {
  const { certificateFiles } = this.data
  const updates = {
    "formData.contractor.license1": "",
    "formData.contractor.license2": ""
  }
  
  // 根据当前上传的文件更新字段
  if (certificateFiles.length > 0) {
    updates["formData.contractor.license1"] = certificateFiles[0].fileName
  }
  if (certificateFiles.length > 1) {
    updates["formData.contractor.license2"] = certificateFiles[1].fileName
  }
  console.log(certificateFiles)
  
  this.setData(updates, () => {
    console.log('当前 license 字段:', {
      license1: this.data.formData.contractor.license1,
      license2: this.data.formData.contractor.license2
    })
})},

  // 显示日期选择器
  showDatePicker() {
    this.setData({ showDatePopup: true })
  },

  // 关闭日期选择器
  closeDatePicker() {
    this.setData({ showDatePopup: false })
  },

  // 确认日期选择
  onDateConfirm(e) {
    const date = new Date(e.detail)
    const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`

    this.setData({
      "formData.contractor.startDate": dateStr,
      showDatePopup: false,
    })
  },

  // 显示类型选择器
  showTypePicker() {
    this.setData({ showTypePopup: true })
  },

  // 新增：统一处理表单字段更新
  onFieldChange(e) {
    const { field, section } = e.currentTarget.dataset;
    const value = e.detail;

    // 构造更新路径
    let updatePath = `formData`;
    if (section) updatePath += `.${section}`;
    updatePath += `.${field}`;

    this.setData({
      [updatePath]: value
    });
  },

  // 关闭类型选择器
  closeTypePicker() {
    this.setData({ showTypePopup: false })
  },

  // 确认类型选择
  onTypeConfirm(e) {
    const { value } = e.detail

    this.setData({
      "formData.decorationType": value,
      showTypePopup: false,
    })
  },

  // 协议同意变化
  onAgreementChange(e) {
    this.setData({
      agreed: e.detail,
    })
  },

  // 查看协议
  viewAgreement(e) {
    const { type } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/agreement/agreement?type=${type}`,
    })
  },


  // 加载用户房屋
  loadUserHouses() {
    wx.showLoading({ title: "加载中..." });
    request.get("/property/house/myHouses").then((res) => {
      if (res.code === 200) {
        const houseOptions = res.data.map((item) => ({
          text: `${item.communityName} ${item.buildingName} ${item.unitName} ${item.floor} ${item.doorNumber}`,
          value: item.roomId.toString(),
        }));
        this.setData({ houseOptions });
      } else {
        wx.showToast({ title: "加载房屋失败", icon: "none" });
      }
      wx.hideLoading();
    }).catch((err) => {
      console.error(err);
      wx.hideLoading();
      wx.showToast({ title: "加载房屋失败", icon: "none" });
    });
  },


  // 提交表单
  onSubmit() {
    this.setData({ submitting: true })
    this.data.formData.contractor.renovationType="毛坯房装修"
    this.data.formData.contractor.renovationProducts="2222222"

    // 模拟提交
    request.post("/property/renovation",{
      contractor:this.data.formData.contractor,
      houseId: this.data.formData.houseId,
    })
    setTimeout(() => {
      this.setData({ submitting: false })

      wx.showToast({
        title: "提交成功",
        icon: "success",
      })

      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }, 2000)
  },
})
